import React, { useCallback, useEffect } from 'react';
import { Button, Space, Spin, Tooltip } from 'antd';
import { features, useTablePipeline } from 'ali-react-table';
import { connect } from 'umi';

import { TRDefault, TRMessage } from '#/components';
import { UploadOutlined } from '#/utils/antdIcons';
import { HttpCode } from '#/utils/contacts';

import { PageLoading } from '@/components';
import { useExcel } from '@/hooks';
import { TjTable, useTRState } from '@/pages/ETrade/components';

import { default as HeadForm } from './form';
import { getElectricityDetailList, queryMarketList } from './services';
import { tableColumns } from './helper';
import styles from './index.less';
import { getTreeByCodes } from '@/utils';

const FreeSettlementDetails = (props) => {
  /** data */
  const exportKey = 'electricitySettlementDetailExport';
  const { menuCode, buttonPermissions } = props;
  const [state, setState] = useTRState({
    canExport: buttonPermissions.some((item) => item.menuCode === exportKey),
    // 初始化三件套
    spinning: true,
    error: '',
    power: [],
    // 数据
    loading: true,
    tableData: [],
  });

  useEffect(() => {
    init();
  }, []);

  /** apis */
  const init = async () => {
    // 权限
    const res = await queryMarketList(menuCode);
    let power = [];
    let error = '';
    if (res?.statusCode === HttpCode.SUCCESS) {
      power = getTreeByCodes(['market', 'group', 'station'], res.json).treeOptions;
    } else {
      error = res?.message || '系统异常';
    }
    setState({
      power,
      error,
      spinning: false,
    });
  };

  /** methods */
  const fmtRes = (res) => {
    const { dataList, totalBody } = res || {};
    if (!dataList?.length) return [];
    const total = {
      ...totalBody,
      stationName: '结算月份 合计',
      statementId: '-',
      transactionTypeName: '-',
      taxRate: '-',
    };
    const bodys = dataList.map((x) => ({
      ...x,
      stationName: `结算月份 ${x.stationName.replace('-', '')}`,
    }));
    return [total, ...bodys];
  };

  const _onChangeForm = async (values) => {
    setState({ loading: true });
    const res = await getElectricityDetailList(values);
    const tableData = fmtRes(res);
    setState({
      tableData,
      loading: false,
    });
  };

  const _onExport = () => {
    // 导出
    if (!state.canExport) return TRMessage.info('请联系管理员获取相关权限');
    let exportData = [state.tableData[0]]; // 合计
    state.tableData.slice(1).map(({ children, ...x }) => {
      exportData.push(x);
      exportData = exportData.concat(children);
    });
    useExcel({
      filename: '电费结算明细',
      columns: tableColumns,
      data: exportData,
      merges: ['stationName'],
    });
  };

  /** render */
  const getColumns = useCallback(() => {
    return tableColumns.map((x) => {
      let { tooltip, ...column } = x;
      if (tooltip) {
        column.render = (v) => (
          <Tooltip placement="top" title={v}>
            <div className={styles.textover}>{v}</div>
          </Tooltip>
        );
      }
      return column;
    });
  }, [tableColumns]);

  const pipeline = useTablePipeline()
    .input({ columns: getColumns(), dataSource: state.tableData })
    .primaryKey('tableId')
    .use(features.rowGrouping({ defaultOpenAll: true }))
    .use(features.autoRowSpan())
    .appendRowPropsGetter((record, rowIndex) => {
      const hasBg = !!record.children || rowIndex === 0;
      const color = hasBg ? '#2D3133' : '#222629';
      return {
        style: { '--bgcolor': color, '--hover-bgcolor': color },
      };
    });

  const _renderTable = () => {
    if (state.loading) return null;
    if (!state.tableData?.length) return <TRDefault type="empty" />;
    return <TjTable useVirtual="auto" {...pipeline.getProps()} />;
  };

  if (state.spinning) return <PageLoading />;
  if (state.error) return <TRDefault type="error" message={state.error} />;
  if (!state.power?.length) return <TRDefault type="lock" />;
  return (
    <Spin spinning={state.loading}>
      <div className={styles.content}>
        <div className={styles.head}>
          <HeadForm power={state.power} onChange={_onChangeForm} />
          <Space size={16} wrap>
            <Button
              disabled={!state.tableData?.length}
              style={{ padding: 0 }}
              type="link"
              icon={<UploadOutlined />}
              onClick={_onExport}
            >
              导出
            </Button>
          </Space>
        </div>
        <div className={styles.main}>
          <div className={styles.box}>
            <div className={styles.flexcolumn}>
              <div className={styles.title}>电费结算明细</div>
              <div className={styles.table}>{_renderTable()}</div>
            </div>
          </div>
        </div>
      </div>
    </Spin>
  );
};

export default connect(({ global }) => ({
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
}))(FreeSettlementDetails);
